package com.cobra.controller;

import cn.hutool.core.text.csv.CsvData;
import cn.hutool.core.text.csv.CsvReader;
import cn.hutool.core.text.csv.CsvRow;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cobra.util.EncodeUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.CharsetUtil;

import java.io.*;
import java.nio.charset.Charset;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class FileUploadController {

    private static String tempFileRootPath = "data/tempFile/";


    @RequestMapping("/list")
    public String upLoadList(@RequestParam(name = "file") MultipartFile[] files, String data) {
        JSONArray array = new JSONArray();
        for (MultipartFile file : files) {
            array.add(file.getOriginalFilename());
        }
        array.add(data);
        return array.toJSONString();
    }

    @RequestMapping("/temp")
    public String temp(@RequestParam(name = "file") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String[] split = originalFilename.split("\\.");
        File tempFile = File.createTempFile(split[0], split[1]);
        String absolutePath = tempFile.getAbsolutePath();
        tempFile.delete();
        return absolutePath;
    }

    @RequestMapping("/read")
    public String read(@RequestParam(name = "file") MultipartFile file) throws Exception {
        Reader read = new InputStreamReader(file.getInputStream(), "UTF-8");
        BufferedReader reader = new BufferedReader(read);
        StringBuffer buffer = new StringBuffer();
        String tmpString = null;
        while ((tmpString = reader.readLine()) != null) {
            buffer.append(tmpString).append("\n");
        }
        return buffer.toString();
    }

    @RequestMapping("/getCsv")
    public String getCsv(@RequestParam(name = "file") MultipartFile file) throws Exception {
        JSONObject result = new JSONObject();
        String originalFilename = file.getOriginalFilename();
        String uuid = IdUtil.randomUUID().replaceAll("-", "");
        String fileName = tempFileRootPath + uuid + System.currentTimeMillis() + "/" + originalFilename;
        File tempFile = createFile(fileName);
        file.transferTo(tempFile.getAbsoluteFile());
        CsvReader csvReader = CsvUtil.getReader();
        CsvData data = csvReader.read(tempFile, Charset.forName(EncodeUtil.getEncode(fileName,false)));
        int rowCount = data.getRowCount();
        List<CsvRow> rows = data.getRows();
        JSONArray array = new JSONArray();
        rows.forEach(row->{
            List<String> rawList = row.getRawList();
            array.add(rawList.toString());
        });
        result.put("path", fileName);
        result.put("count", rowCount);
        result.put("array",array);
        deleteFile(tempFile);
        return result.toJSONString();
    }




    private void deleteFile(File tempFile) {
        File parentDir = tempFile.getParentFile();
        //删除当前文件
        tempFile.delete();
        //删除父目录
        parentDir.delete();
    }

    private File createFile(String fileName) throws IOException {
        File file = new File(fileName);
        File parentFile = file.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        file.createNewFile();
        return file;
    }


}
